package com.example.communication;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangs
 * @version v1.0
 * @decription 线程通信
 * @date 2021/3/28 12:50
 **/
public class WaitAndNotify {
    final static Object LOCK = new Object();

    public static void main(String[] args) {
        new Thread(()->{
            synchronized (LOCK) {
                Thread curr = Thread.currentThread();
                System.out.println(curr.getName() + " start!");
                try {
                    // 阻塞当前线程，并释放锁
                    LOCK.wait();
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(curr.getName()+" end!");
            }
        },"t1").start();

        new Thread(()->{
            synchronized (LOCK) {
                Thread curr = Thread.currentThread();
                System.out.println(curr.getName() + " start!");
                // 唤醒阻塞在LOCK上的线程
                LOCK.notify();
                try {
                    // 当前线程休眠两秒
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(curr.getName()+" end!");
                System.out.println("notify 方法不会释放锁!");
            }
        },"t2").start();
    }
}
